﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Backend.JYD.BLL;
using Backend.JYD.RunTime;
using Backend.JYD.Model.Cust;
using Backend.JYD.Common;
using Backend.JYD.BLL.Cust;
using Backend.JYD.Business;
using Backend.JYD.Model.Task;
using Backend.JYD.BLL.Task;
using Backend.JYD.RunTime.Attribute;
using System.Data.Entity.Validation;

namespace Backend.JYD.Web.Controllers
{
    public class MarketingController : BaseController
    {
        CustMarketingInfoBLL bll = new CustMarketingInfoBLL();
         [AuthorityFilter(AuthorCode.AuthorCode_TaskMarketing, AuthorCode.AuthorCode_Marketing, AuthorCode.AuthorCode_MarketingManager)]
        public ActionResult Index(int? page, DateTime? start, DateTime? end, int? status)
        {
            var list = bll.GetCustMarketingInfoByPage(this.EmpId, start, end, status, new Model.PageInfo() { PageIndex = page ?? 1, PageSize = 20 });
            if (list == null) return View();

            List<long> ids = new List<long>();
            foreach (var info in list.PageList)
            {
                if (info.OpId.HasValue && !ids.Contains(info.OpId.Value)) ids.Add(info.OpId.Value);
            }
            if (ids != null && ids.Count > 0)
            {
                ids = ids.Distinct().ToList();
                this.ViewBag.EmpInfos = new EmpInfoBLL().GetEmpInfoByEmpIds(ids, true);
            }

            this.ViewBag.PageIndex = list.PageIndex;
            this.ViewBag.PageSize = list.PageSize;
            this.ViewBag.PageCount = list.PageCount;
            this.ViewBag.ItemCount = list.ItemCount;
            string url = "/task/index?page={0}";
            if (start.HasValue)
            {
                ViewBag.StartDate = DateTimeHelper.GetDateShortFormat(start.Value);
                url += "&start=" + DateTimeHelper.GetDateShortFormat(start.Value);
            }
            if (end.HasValue)
            {
                ViewBag.EndDate = DateTimeHelper.GetDateShortFormat(end.Value);
                url += "&end=" + DateTimeHelper.GetDateShortFormat(end.Value);
            }
            if (status.HasValue)
            {
                ViewBag.Status = status;
                url += "&status=" + status;
            }

            ViewBag.PageUrl = url;
            return View(list.PageList);
        }

        [AuthorityFilter(AuthorCode.AuthorCode_TaskMarketing, AuthorCode.AuthorCode_Marketing, AuthorCode.AuthorCode_MarketingManager)]
        public ActionResult Create(Int64? tid, Int64? did)
        {
            if (tid.HasValue && did.HasValue && tid.Value > 0 && did.Value > 0)
            {
                var taskInfo = new TaskBaseInfoBLL().GetTaskBaseInfoByTaskId(tid.Value);
                var info = bll.GetCustMarketingInfoByTaskDetailId(tid, did.Value);
                if (info != null)
                {
                    if (info.Status == 1)
                        return RedirectToAction("process");
                    else
                        return RedirectToAction("details", new { id = info.MarketingId });
                }
                else
                {
                    if (taskInfo == null) return View("Error");

                    IntentEntryInfo intent = new IntentEntryInfoBLL().GetIntentEntryInfoByIntentId(taskInfo.IntentId);
                    if (intent == null) return View("Error");

                    info = new CustMarketingInfo();
                    info.TaskDetailId = did.Value;
                    info.TaskId = tid.Value;
                    info.CustName = intent.CustName;
                    info.CustNo = intent.CustNo;
                    info.Phone = intent.Phone;
                    info.PaperNo = intent.PaperNo;
                    info.PaperType = intent.PaperType;
                }
                
                this.ViewBag.TaskInfo = taskInfo;
                this.ViewBag.TaskId = tid;
                this.ViewBag.TaskDetailId = did;
                return View(info);
            }
            return View();
        }

        [HttpPost]
        [AuthorityFilter(AuthorCode.AuthorCode_TaskMarketing, AuthorCode.AuthorCode_Marketing, AuthorCode.AuthorCode_MarketingManager)]
        public ActionResult Create(CustMarketingInfo info)
        {
            try
            {
                if (info.TaskDetailId > 0 && info.TaskId > 0)
                {
                    var taskInfo = new TaskBaseInfoBLL().GetTaskBaseInfoByTaskId(info.TaskId);
                    IntentEntryInfo intent = new IntentEntryInfoBLL().GetIntentEntryInfoByIntentId(taskInfo.IntentId);
                    info.CustName = intent.CustName;
                    info.CustNo = intent.CustNo;
                    info.Phone = intent.Phone;
                    info.PaperNo = intent.PaperNo;
                    info.PaperType = intent.PaperType;
                }

                //var info = new CustMarketingInfo();
                info.CreateTime = DateTime.Now;
                //info.ScheduleTime = DateTimeHelper.Str2DateTime(collection["ScheduleTime"], DateTime.MinValue);
                info.OpId = this.EmpId;
                info.Status = 1;
                info.Type = 1;
                info.UpdateTime = DateTime.Now;
                //info.ValidDays = NumberHelper.StrToInt(collection["ValidDays"], 0);
                //info.CustNo = collection["CustNo"];
                //info.Memo = collection["Memo"];
                //info.TaskId = NumberHelper.StrToInt64(collection["TaskId"], 0);
                //info.TaskDetailId = NumberHelper.StrToInt64(collection["TaskDetailId"], 0);

                var markId = bll.AddCustMarketingInfo(info);
                if (markId > 0)
                {
                    if (info.TaskId > 0 && info.TaskDetailId > 0)
                    {
                        new TaskManager().BeginProcessStep(info.TaskId, this.EmpId, "创建营销任务");
                    }
                }
                return Json(new { code = markId > 0 });
            }
            catch (Exception ex)
            {
                LogHelper.Log(ex);
                return Json(new { code = false, msg = "异常" });
            }
        }

        [AuthorityFilter(AuthorCode.AuthorCode_TaskMarketing, AuthorCode.AuthorCode_Marketing, AuthorCode.AuthorCode_MarketingManager)]
        public ActionResult Edit(int id)
        {
            var info = bll.GetCustMarketingInfoByMarketingId(this.EmpId, id);
            if (info != null)
            {
                return View(info);
            }
            else
            {
                return RedirectToAction("index");
            }
        }

        [AuthorityFilter(AuthorCode.AuthorCode_TaskMarketing, AuthorCode.AuthorCode_Marketing, AuthorCode.AuthorCode_MarketingManager)]
        public ActionResult Details(int id)
        {
            var info = bll.GetCustMarketingInfoByMarketingId(this.EmpId, id);

            return View(info);
        }

        [HttpPost]
        [AuthorityFilter(AuthorCode.AuthorCode_TaskMarketing, AuthorCode.AuthorCode_Marketing, AuthorCode.AuthorCode_MarketingManager)]
        public ActionResult Edit(Int64 id, FormCollection collection)
        {
            try
            {
                Int64 cid = NumberHelper.StrToInt64(collection["MarketingId"]);
                if (cid != id)
                {
                    return Json(new { code = false, msg = "错误的请求。" });
                }
                var info = bll.GetCustMarketingInfoByMarketingId(this.EmpId, id);
                if (info == null)
                {
                    return Json(new { code = false, msg = "错误的Id" });
                }
                info.ScheduleTime = DateTimeHelper.Str2DateTime(collection["ScheduleTime"], DateTime.MinValue);
                if (info.TouchTime < DateTime.Now)
                {
                    return Json(new { code = false, msg = "计划接触时间，不能小于当前时间。" });
                }
                info.UpdateTime = DateTime.Now;
                info.Memo = collection["Memo"];
                info.ValidDays = NumberHelper.StrToInt(collection["ValidDays"], 1);

                bool success = bll.UpdateCustMarketingInfo(info);
                return Json(new { code = success, msg = success ? string.Empty : "更新失败" });
            }
            catch (Exception ex)
            {
                LogHelper.Log(ex);
                return Json(new { code = false, msg = "异常" });
            }
        }

        [AuthorityFilter(AuthorCode.AuthorCode_TaskMarketing, AuthorCode.AuthorCode_Marketing, AuthorCode.AuthorCode_MarketingManager)]
        public ActionResult Process(int id)
        {
            var info = bll.GetCustMarketingInfoByMarketingId(this.EmpId, id);
            if (info != null)
            {
                this.ViewBag.CustMarketingInfo = info;
                this.ViewBag.CustInfo = new CustBaseBLL().GetCustBaseInfo(info.CustNo);
                if (info.TaskId > 0 && info.TaskDetailId > 0)
                {
                    var taskInfo = new TaskBaseInfoBLL().GetTaskBaseInfoByTaskId(info.TaskId);
                    var model = new TaskStepModelBLL().GetTaskStepModelByTaskModeIdAndStepId(taskInfo.TaskModelId, taskInfo.StepId);
                    this.ViewBag.StepModel = model;
                }
            }

            return View(info);
        }


        [HttpPost]
        [AuthorityFilter(AuthorCode.AuthorCode_TaskMarketing, AuthorCode.AuthorCode_Marketing, AuthorCode.AuthorCode_MarketingManager)]
        public ActionResult Process(int id, FormCollection collection)
        {
            try
            {
                Int64 cid = NumberHelper.StrToInt64(collection["MarketingId"]);
                #region 验证
                
                if (cid != id)
                {
                    return Json(new { code = false, msg = "错误的请求。" });
                }
                var info = bll.GetCustMarketingInfoByMarketingId(this.EmpId, id);
                if (info == null)
                {
                    return Json(new { code = false, msg = "错误的Id" });
                }
                info.TouchTime = DateTimeHelper.Str2DateTime(collection["TouchTime"], DateTime.MinValue);
                if (info.TouchTime > DateTime.Now)
                {
                    return Json(new { code = false, msg = "实际接触时间，不能大于当前时间。" });
                }

                #endregion
                #region 验证

                info.UpdateTime = DateTime.Now;
                info.Remark = collection["Remark"];
                info.Ways = collection["Ways"];
                int status = NumberHelper.StrToInt(collection["Status"]);
                if (info.Status == 1 && (status == 2 || status == 4 || status == 5))
                {
                    info.Status = status;
                }

                #endregion

                bool success = bll.UpdateCustMarketingInfo(info);
                if (success)
                {
                    info = bll.GetCustMarketingInfoByMarketingId(this.EmpId, info.MarketingId);
                    //这个逻辑有问题。
                    if (info.TaskId > 0 && info.TaskDetailId > 0)
                    {
                        #region task
                        
                        var taskInfo = new TaskBaseInfoBLL().GetTaskBaseInfoByTaskId(info.TaskId);
                        var model = new TaskStepModelBLL().GetTaskStepModelByTaskModeIdAndStepId(taskInfo.TaskModelId, taskInfo.StepId);
                        if (info.Status == (int)TaskManager.TaskStatus.CompleteAndReady && !string.IsNullOrWhiteSpace(model.NextStepIds))
                        {
                            //var ids = StringHelper.String2List<Int64>(model.UseRole ? model.RoleIds : model.EmpIds);
                            var steps = StringHelper.String2List<Int32>(model.NextStepIds);
                            new TaskManager().NextStep(info.TaskId, null, TaskManager.TaskStatus.CompleteAndReady, steps.First(), info.Remark, this.EmpId);
                        }
                        if (info.Status == (int)TaskManager.TaskStatus.CompleteAndLoop && model.AllowLoop)
                        {
                            new TaskManager().NextStep(info.TaskId, null, TaskManager.TaskStatus.CompleteAndLoop, null, info.Remark, this.EmpId);
                          
                            //return Json(new { code = true, open = true, tid = info.TaskId, did = info.TaskDetailId });
                        }
                        if (info.Status == (int)TaskManager.TaskStatus.Complete && model.AllowStop)
                        {
                            //???
                            new TaskManager().NextStep(info.TaskId, null, TaskManager.TaskStatus.Complete, null, info.Remark, this.EmpId);
                        }

                        #endregion
                    }
                    if (info.Status == (int)TaskManager.TaskStatus.CompleteAndLoop)
                    {
                        #region Next - loop
              
                        var next = new CustMarketingInfo();
                        next.CustName = info.CustName;
                        next.CustNo = info.CustNo;
                        next.PaperNo = info.PaperNo;
                        next.PaperType = info.PaperType;
                        next.Phone = info.Phone;
                        next.CreateTime = DateTime.Now;
                        next.ScheduleTime = DateTimeHelper.Str2DateTime(collection["ScheduleTime"], DateTime.MinValue);
                        next.OpId = this.EmpId;
                        next.Status = 1;
                        next.Type = 1;
                        next.UpdateTime = DateTime.Now;
                        next.ValidDays = NumberHelper.StrToInt(collection["ValidDays"], 0);
                        next.Memo = collection["Memo"];
                        if (info.TaskId > 0)
                        {
                            var taskInfo = new TaskBaseInfoBLL().GetTaskBaseInfoByTaskId(info.TaskId);
                            if (taskInfo != null)
                            {
                                next.TaskId = taskInfo.TaskId;
                                next.TaskDetailId = !taskInfo.TaskDetailId.HasValue ? 0 : taskInfo.TaskDetailId.Value;
                            }
                        }
                        var markId = bll.AddCustMarketingInfo(next);
                        if (markId > 0)
                        {
                            if (info.TaskId > 0 && info.TaskDetailId > 0)
                            {
                                new TaskManager().BeginProcessStep(info.TaskId, this.EmpId, "创建营销任务");
                            }
                        }

                        #endregion
                    }
                }
                return Json(new { code = success });
            }
            catch (Exception ex)
            {
                LogHelper.Log(ex);
                return Json(new { code = false, msg = "异常" });
            }
        }
    }
}
